<?php defined("ROOT") or exit("access deny")?>
<!DOCTYPE html>
<html lang="zh-cn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
    <title>Y_CMS图床</title>
    <link rel="stylesheet" href="http://cdn.bootcss.com/bootswatch/3.3.4/readable/bootstrap.min.css" type="text/css" media="all" />
    <style type="text/css">
        .setting-msg {
            display: none;
        }
        .upload-box {
            border: 2px dashed rgb(114, 188, 240);
            height: 200px;
            cursor: pointer;
        }
        .upload-box p {
            padding-top: 88px;
            display: block;
            width: 50%;
            margin: 0 auto;
            line-height: 20px;
        }
        .progress-box {
            margin-top: 20px;
            padding: 5px;
        }
        .progress {
            margin-bottom: 0px;
        }
        .img-box {
            height: 250px;
        }
        .img-box a {
            display: block;
            height: 210px;
        }
        .img-box img {
            width: 100%;
            max-height: 210px;
        }
        .img-box input {
            margin-top: 8px;
            height: 23px;
        }
        .file-box .file {
            font-size: 100px;
        }
        .file-box a {
            color: rgb(176, 199, 229);
            padding-top: 50px;
        }
    </style>
</head>
<body>
<nav class="navbar navbar-default">
    <div class="container-fluid">
        <!-- Brand and toggle get grouped for better mobile display -->
        <div class="navbar-header">
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="#">Y_CMS图床</a>
        </div>

        <!-- Collect the nav links, forms, and other content for toggling -->
        <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">


        </div><!-- /.navbar-collapse -->
    </div><!-- /.container-fluid -->
</nav>
<div class="container main">

    <div class="row">
        <div class="col-md-8">
            <div class="row resutl-box">
            </div>
        </div>
        <div class="col-md-4">
            <div class="row">
                <div class="col-md-12">
                    <div class="upload-box">
                        <p>
                            点击、或者拖拽文件到此
                        </p>
                    </div>
                </div>
            </div>
            <div class="row progress-box">
                <div class="col-md-12">
                </div>
            </div>
        </div>
    </div>
</div>


<script src="http://cdn.bootcss.com/jquery/2.1.3/jquery.min.js"></script>
<script src="http://cdn.bootcss.com/dropzone/4.0.1/min/dropzone.min.js"></script>
<script src="http://cdn.bootcss.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<script src="http://cdn.bootcss.com/unveil/1.3.0/jquery.unveil.min.js"></script>
<script src="http://cdn.bootcss.com/store.js/1.3.14/store.min.js"></script>
<script src="http://cdn.bootcss.com/crypto-js/3.1.2/rollups/hmac-sha1.js"></script>
<script src="http://cdn.bootcss.com/crypto-js/3.1.2/components/enc-base64-min.js"></script>
<script>
    function utf16to8(str) {
        var out, i, len, c;
        out = "";
        len = str.length;
        for (i = 0; i < len; i++) {
            c = str.charCodeAt(i);
            if ((c >= 0x0001) && (c <= 0x007F)) {
                out += str.charAt(i);
            } else if (c > 0x07FF) {
                out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));
                out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F));
                out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
            } else {
                out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F));
                out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
            }
        }
        return out;
    }

    function utf8to16(str) {
        var out, i, len, c;
        var char2, char3;
        out = "";
        len = str.length;
        i = 0;
        while (i < len) {
            c = str.charCodeAt(i++);
            switch (c >> 4) {
                case 0:
                case 1:
                case 2:
                case 3:
                case 4:
                case 5:
                case 6:
                case 7:
                    // 0xxxxxxx
                    out += str.charAt(i - 1);
                    break;
                case 12:
                case 13:
                    // 110x xxxx 10xx xxxx
                    char2 = str.charCodeAt(i++);
                    out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F));
                    break;
                case 14:
                    // 1110 xxxx 10xx xxxx 10xx xxxx
                    char2 = str.charCodeAt(i++);
                    char3 = str.charCodeAt(i++);
                    out += String.fromCharCode(((c & 0x0F) << 12) | ((char2 & 0x3F) << 6) | ((char3 & 0x3F) << 0));
                    break;
            }
        }
        return out;
    }

    /*
     * Interfaces:
     * b64 = base64encode(data);
     * data = base64decode(b64);
     */
    var base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
    var base64DecodeChars = new Array(-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63,
        52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
        15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
        41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1);

    function base64encode(str) {
        var out, i, len;
        var c1, c2, c3;
        len = str.length;
        i = 0;
        out = "";
        while (i < len) {
            c1 = str.charCodeAt(i++) & 0xff;
            if (i == len) {
                out += base64EncodeChars.charAt(c1 >> 2);
                out += base64EncodeChars.charAt((c1 & 0x3) << 4);
                out += "==";
                break;
            }
            c2 = str.charCodeAt(i++);
            if (i == len) {
                out += base64EncodeChars.charAt(c1 >> 2);
                out += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
                out += base64EncodeChars.charAt((c2 & 0xF) << 2);
                out += "=";
                break;
            }
            c3 = str.charCodeAt(i++);
            out += base64EncodeChars.charAt(c1 >> 2);
            out += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
            out += base64EncodeChars.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6));
            out += base64EncodeChars.charAt(c3 & 0x3F);
        }
        return out;
    }

    function base64decode(str) {
        var c1, c2, c3, c4;
        var i, len, out;
        len = str.length;
        i = 0;
        out = "";
        while (i < len) {
            /* c1 */
            do {
                c1 = base64DecodeChars[str.charCodeAt(i++) & 0xff];
            } while (i < len && c1 == -1);
            if (c1 == -1) break;
            /* c2 */
            do {
                c2 = base64DecodeChars[str.charCodeAt(i++) & 0xff];
            } while (i < len && c2 == -1);
            if (c2 == -1) break;
            out += String.fromCharCode((c1 << 2) | ((c2 & 0x30) >> 4));
            /* c3 */
            do {
                c3 = str.charCodeAt(i++) & 0xff;
                if (c3 == 61) return out;
                c3 = base64DecodeChars[c3];
            } while (i < len && c3 == -1);
            if (c3 == -1) break;
            out += String.fromCharCode(((c2 & 0XF) << 4) | ((c3 & 0x3C) >> 2));
            /* c4 */
            do {
                c4 = str.charCodeAt(i++) & 0xff;
                if (c4 == 61) return out;
                c4 = base64DecodeChars[c4];
            } while (i < len && c4 == -1);
            if (c4 == -1) break;
            out += String.fromCharCode(((c3 & 0x03) << 6) | c4);
        }
        return out;
    }
    var safe64 = function(base64) {
        base64 = base64.replace(/\+/g, "-");
        base64 = base64.replace(/\//g, "_");
        return base64;
    };
    var genToken = function(accessKey, secretKey, putPolicy) {
        var setStep = function(id, val) {
            // Ext.getCmp(id).setValue("<div style=\"color:blue;word-break: break-all;font-size:18px;line-height:28px;\"><b>" + val + "</b></div>");
        }
        //SETP 2
        var put_policy = JSON.stringify(putPolicy);
        console.log("put_policy = ", put_policy);

        setStep("disp_step2", put_policy);

        //SETP 3
        var encoded = base64encode(utf16to8(put_policy));
        console.log("encoded = ", encoded);
        setStep("disp_step3", encoded);

        //SETP 4
        var hash = CryptoJS.HmacSHA1(encoded, secretKey);
        var encoded_signed = hash.toString(CryptoJS.enc.Base64);
        setStep("disp_step4", encoded_signed);

        //SETP 5
        var upload_token = accessKey + ":" + safe64(encoded_signed) + ":" + encoded;
        setStep("disp_step5", upload_token);

        return upload_token;
    };

    var getManageToken = function(accessKey, secretKey, signingStr) {

        var hash = CryptoJS.HmacSHA1(signingStr, secretKey);
        var encoded_signed = hash.toString(CryptoJS.enc.Base64);
        var accessToken = accessKey + ':' + safe64(encoded_signed);
        return accessToken;
    };

    var getListToken = function(accessKey, secretKey, params) {

        var listSpec = 'bucket=' + params.bucket;
        if (params.limit) {
            listSpec += '&' + 'limit=' + params.limit;
        }
        if (params.prefix) {
            listSpec += '&' + 'prefix=' + params.prefix;
        }
        var signingStr = '/list?' + listSpec + '\n';
        console.log('signingStr = ' + signingStr);
        var accessToken = getManageToken(accessKey, secretKey, signingStr);
        console.log('accessToken = ' + accessToken);
        return {
            at: accessToken,
            path: signingStr
        };
    };

    var getDeleteToken = function(accessKey, secretKey, bucket, key) {
        var entry = bucket + ':' + key;
        var signingStr = '/delete/' + safe64(base64encode(entry)) + '\n';
        console.log('signingStr = ' + signingStr);
        var accessToken = getManageToken(accessKey, secretKey, signingStr);
        console.log('accessToken = ' + accessToken);
        return {
            at: accessToken,
            path: signingStr
        };
    }
</script>

<script>
    function getToken() {

        var expires = 3600;
        var policy = new Object();
        var bucketName = "Y_CMS-v1";
        var accessKey = "16UtFTryGnDJhcFrji1TYVKB-MK_axGzkmu5BVuP";
        var secretKey = "HJKacVbPdmM2m9AOGKsb55DetHMfmmwfRrAToZQK";
        policy.scope = bucketName;
        var name = Math.floor((Math.random() * 1000));
        policy.saveKey = '$(year)/$(mon)/$(day)/$(etag)' + name + '$(ext)';
        var returnBody = {
            key: '$(key)',
            origin_name: '$(fname)',
            hash: '$(etag)',
            width: '$(imageInfo.width)',
            height: '$(imageInfo.height)',
            type: '$(mimeType)'
        };
        policy.returnBody = JSON.stringify(returnBody);
        var deadline = Math.round(new Date().getTime() / 1000) + expires;
        policy.deadline = deadline;
        console.log(policy);
        var uptoken = genToken(accessKey, secretKey, policy);
        return uptoken;
    }
    function createProgress(file) {
        var $progressWrapper = $('<div></div>');
        $progressWrapper.addClass('progress-wrapper');

        var $progress = $('<div></div>');
        $progress.addClass('progress');
        var $progressBar = $('<div></div>');
        $progressBar.addClass('progress-bar');
        $progressBar.addClass('progress-bar-success');
        $progressBar.css('width', '0%');
        $progressBar.appendTo($progress);

        var $progressText = $('<div></div>');
        $progressText.addClass('progress-text');
        $progressText.addClass('text-center');
        $progressText.text(file.name);

        $progressWrapper.append($progress);
        $progressWrapper.append($progressText);
        return $progressWrapper;
    }
    function createResultImage(img) {
        var url = "http://oi7kb12ow.bkt.clouddn.com/" + img.key;
        var $img;
        if (img.type.startsWith('image')) {
            $img = $('<div class="col-md-4" style="display:none;"> \
                            <div class="thumbnail img-box">\
                                <a href="'+url+'" target="_blank">\
                                    <img src="'+url+'">\
                                </a>\
                                <input type="text" class="form-control input-sm" value="'+url+'">\
                            </div>\
                        </div>');
        } else {
            $img = $('<div class="col-md-4" style="display:none;"> \
                            <div class="thumbnail img-box file-box">\
                                <a href="'+url+'" target="" class="text-center">\
                                    <span class="glyphicon glyphicon-file file" aria-hidden="true"></span>\
                                </a>\
                                <input type="text" class="form-control input-sm" value="'+url+'">\
                            </div>\
                        </div>');
        }
        return $img;
    }
    $(function() {
        var files = store.get('files');
        if (files) {
            $.each(files, function(k, v) {
                var $img = createResultImage(v);
                $('.resutl-box').prepend($img);
                $img.show();
            });
        }
        $(".upload-box").dropzone({
            url: "http://up-z1.qiniu.com",
            clickable: true,
            maxFilesize: 10,
            maxFiles: 5,
            params: {
            },
            success: function(file, data) {
                var $img = createResultImage(data);
                var files = store.get('files');
                if (!files) {
                    files = [];
                }
                files.push(data);
                store.set('files', files);
                $('.resutl-box').prepend($img);
                $img.slideDown(function() {
                    file.progress.fadeIn('slow', function() {
                        $(this).remove();
                    });
                });
                console.log(data);
            },
            maxfilesexceeded: function(file) {
                file.progress.remove();
            },
            addedfile: function(file) {
                this.options.params.token = getToken();
                var $progress = createProgress(file);
                $('.progress-box .col-md-12').append($progress);
                file.progress = $progress;
                $('.upload-box p').css('padding-top', 44);
                /* $('.upload-box').css('height', 100); */
                $('.upload-box').animate({
                    height: "100px"
                }, 500);
            },
            uploadprogress: function(file, progress, bytesSent) {
                file.progress.find('.progress-bar').css('width', progress + '%');
                file.progress.find('.progress-bar').text(progress.toFixed(2) + '%');
            },
            queuecomplete: function() {
                $('.upload-box p').css('padding-top', 88);
                $('.upload-box').animate({
                    height: "200px"
                }, 500);
            }
        });

        $('.resutl-box').on('mouseenter', 'input', function() {
            $(this).select();
        });
        $('.result-box').on('mouseleave', 'input', function() {
            $(this).blur();
        });
    });
</script>
</body>
</html>
